package com.heimali.happyreader.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.heimali.happyreader.HappyReaderApplication;
import com.heimali.happyreader.debug.Console;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class AndroidUtils {

	public static final String TAG = "AndroidUtils";
	
	
	public static float density = 0;
	private static PackageManager pm = null;
	private static ScreenInfo screenInfo = null;
	private static String phoneModel = "UNKNOWN";
	
	public static PackageManager getPackageManager() {
		if (pm == null)
			pm = HappyReaderApplication.getContext().getPackageManager();
		return pm;
	}

	public static PackageInfo getPackageInfo(String packageName) {
		try {
			if (packageName == null)
				packageName = HappyReaderApplication.getContext().getPackageName();
			return getPackageManager().getPackageInfo(packageName, 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void toast(int message) {
		Toast.makeText(HappyReaderApplication.getContext(), message, Toast.LENGTH_SHORT).show();
	}
	
	public static void displayToast(String message) {
		Toast.makeText(HappyReaderApplication.getContext(), message, Toast.LENGTH_SHORT).show();
	}
	
	

	/**
	 * 获得当前终端的UA(型号)
	 * 
	 * @return
	 */
	public static String getPhoneModel() {
		if (TextUtils.isEmpty(phoneModel) || "UNKNOWN".equals(phoneModel)) {
		    if (android.os.Build.MODEL != null) {
		        phoneModel = android.os.Build.MODEL;
		    }
		}
		return phoneModel;
	}

	private static int androidVersion = -1;

	/**
	 * 获得当前apk的anroid版本号 如1.6,2.1,2.2<br/>
	 * 返回值小于0为错误
	 * 
	 * @return
	 */
	public static int getSystemVersionCode() {
		try {
			if (androidVersion <= 0)
				androidVersion = android.os.Build.VERSION.SDK_INT;
		} catch (Exception e) {
			e.printStackTrace();
			androidVersion = -1;
		}
		return androidVersion;
	}

	/**
	 * 获取屏幕信息
	 * 
	 * @return
	 */
	public static ScreenInfo getScreenInfo() {
		DisplayMetrics dm = new DisplayMetrics();
		((WindowManager) HappyReaderApplication.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
				.getMetrics(dm);
		screenInfo = new ScreenInfo();
		screenInfo.density = dm.density;
		screenInfo.screenHeight = dm.heightPixels;
		screenInfo.screenWidth = dm.widthPixels;
		return screenInfo;
	}

	public static class ScreenInfo {
		/**
		 * 终端屏幕分辨率
		 */
		public int screenWidth = -1, screenHeight = -1;
		/**
		 * 密度
		 */
		public float density = -1;
	}

	public static float getDensity() {
		if (density == 0) {
			density = HappyReaderApplication.getContext().getResources().getDisplayMetrics().density;
		}
		return density;
	}

	public static int px2dp(float pxValue) {
		return (int) (pxValue / getDensity() + 0.5);
	}

	public static int dp2px(float dpValue) {
		return (int) (dpValue * getDensity() + 0.5);
	}

	/**
	 * 根据包名获取应用图标
	 * 
	 * @param packageName
	 * @return
	 */
	public static Drawable getApkIcon(String packageName) {
		if (TextUtils.isEmpty(packageName)) {
			return null;
		}

		PackageManager pm = getPackageManager();
		try {
			ApplicationInfo appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
			return pm.getApplicationIcon(appInfo);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 弹出软键盘
	 * 
	 * @param context
	 */
	public static void displaySoftInput(final Context context) {
		// 键盘弹出需要延迟一会才能弹出
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}, 100);
	}

	/**
	 * 多种隐藏软件盘方法的其中一种
	 * 
	 * @param token
	 */
	public static void hideSoftInput(IBinder token) {
		if (token != null) {
			InputMethodManager imm = (InputMethodManager) HappyReaderApplication.getContext().getSystemService(
					Context.INPUT_METHOD_SERVICE);
			if (imm.isActive()) {
				imm.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
	}

	public static boolean checkSoftInputDisplay(IBinder token) {
		if (token != null) {
			InputMethodManager imm = (InputMethodManager) HappyReaderApplication.getContext().getSystemService(
					Context.INPUT_METHOD_SERVICE);
			return imm.isActive();
		}
		return false;
	}

	/**
	 * 版本号
	 */
	private static int VersionCode = 0;
	/**
	 * 版本名称
	 */
	private static String VersionName = "";

	/**
	 * 获取版本号
	 * 
	 * @return
	 */
	public static int getVersionCode() {
		if (VersionCode <= 0) {
			try {
				VersionCode = AndroidUtils.getPackageInfo(null).versionCode;
			} catch (Exception e) {
				VersionCode = 0;
			}
		}
		return VersionCode;
	}

	/**
	 * 获取版本名称
	 * 
	 * @return
	 */
	public static String getVersionName() {
		if (TextUtils.isEmpty(VersionName)) {
			try {
				VersionName = AndroidUtils.getPackageInfo(null).versionName;
			} catch (Exception e) {
				VersionName = "";
			}
		}
		return VersionName;
	}

	/**
	 * 取机器唯一标识
	 */
	private static String _machineID = null;

	public static String getMachineID() {
		if (!TextUtils.isEmpty(_machineID)) {
			return _machineID;
		}

		TelephonyManager tm = (TelephonyManager) HappyReaderApplication.getApplication().getSystemService(
				Context.TELEPHONY_SERVICE);
		String devid = tm.getDeviceId();

		if (TextUtils.isEmpty(devid)) {
			WifiManager wm = (WifiManager) HappyReaderApplication.getApplication().getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wm.getConnectionInfo();
			if (info != null) {
				devid = info.getMacAddress();
			}
		}

		if (TextUtils.isEmpty(devid)) {
			devid = "";
		} else {
			devid = Utils.getMD5(devid);
		}
		_machineID = devid;
		return _machineID;
	}
	
	/**
	 * 检查服务是否正在运行
	 * 
	 * @param serviceClassName
	 * @return
	 */
	public static boolean checkServiceIsRunning(String serviceClassName) {
		ActivityManager activityManager = (ActivityManager) HappyReaderApplication.getContext().getSystemService(
				Context.ACTIVITY_SERVICE);
		final List<RunningServiceInfo> serviceList = activityManager.getRunningServices(100);
		if (serviceList == null || serviceList.size() <= 0) {
			return false;
		}

		for (RunningServiceInfo info : serviceList) {
			if (info.service.getClassName().equals(serviceClassName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取手机内部存储rom的可用空间
	 * 
	 * @return
	 */
	public static long getAvailROMSize() {
		StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		return blockSize * availableBlocks;
	}
	
	
	public static boolean isDataConnected(Context c) {
        if (isWifiConnected(c) || isPhoneDataConnected(c)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * add for check wifi net connection
     * desc:
     * wifi 开关打开，但是wifi没有连上的话仍然是false
     * 只有wifi正常网络已经建立,正常获取IP后才返回true
     * */
    public static boolean isWifiConnected(Context c) {
        WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        DetailedState detailedState = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
        if (isLiveConnection(detailedState)) {
            Console.log(TAG, "isWifiConnected", "wifi connect is ok!");
            return true;
        } else {
        	 Console.log(TAG, "isWifiConnected", "wifi connect is not ok!");
            return false;
        }
    }

    //	/**Wifi的IP为0时说明wifi没有连接上*/
    //	public static int getWifiIp(Context c){
    //    	WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
    //    	WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    //    	int iIp = wifiInfo.getIpAddress();
    //    	Utils.log("network", "=====>wifi IP is "+iIp);
    //    	return iIp;
    //	}
    public static boolean isPhoneDataRealConnected(Context c) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        int iDataState = -1;
        iDataState = mTelephonyMgr.getDataState();
        if (iDataState == TelephonyManager.DATA_CONNECTED) {
        	Console.log(TAG, "network_test===>>>data state is DATA_CONNECTED");
            return true;
        } else {
            return false;
        }
    }

    private static boolean isLiveConnection(NetworkInfo.DetailedState detailedState) {
        return detailedState != NetworkInfo.DetailedState.DISCONNECTED
                && detailedState != NetworkInfo.DetailedState.FAILED && detailedState != NetworkInfo.DetailedState.IDLE
                && detailedState != NetworkInfo.DetailedState.SCANNING;
    }

    /*
     * add for check phone net connection,such as APN
     * desc:
     * 		移动网络数据通信
     * 		
     * */
    public static boolean isPhoneDataConnected(Context c) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        int iDataState = -1;
        iDataState = mTelephonyMgr.getDataState();
        if (iDataState == TelephonyManager.DATA_DISCONNECTED) {
        	Console.log(TAG, "network_test===>>>data state is DATA_DISCONNECTED");
            return false;
        } else {
            return true;
        }
    }
    
    public static String getScreenSize() {
		ScreenInfo sInfo = getScreenInfo();
		return sInfo.screenWidth+"_"+sInfo.screenHeight;
	}
    
    public static String getRandomData() {
    	return Utils.getMD5(String.valueOf(System.currentTimeMillis())).substring(4, 20);
    }

}
